package com.xjcs.saplingplan.room.utils

import androidx.annotation.WorkerThread
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.xjcs.saplingplan.MainApp
import com.xjcs.saplingplan.const.AppMainTab
import com.xjcs.saplingplan.const.getMainAppDefaultTab
import com.xjcs.saplingplan.room.AppDatabase
import com.xjcs.saplingplan.room.bean.AppUserInfo

object AppUserRoomUtils {

    private val appUserDao by lazy {
        AppDatabase.getInstance(MainApp.getAppContext()).appUserDao()
    }

    @WorkerThread
    suspend fun getAppMainTab(userId: String): List<AppMainTab>{
        try {
            val curUserInfo = getAppCurUserInfo(userId)
            return if(curUserInfo == null){
                getMainAppDefaultTab()
            }else{
                GsonUtils.fromJson(curUserInfo.appMainTabList, object: TypeToken<List<AppMainTab>>(){}.type)
            }
        } catch (e: Exception) {
            return getMainAppDefaultTab()
        }
    }

    @WorkerThread
    suspend fun setMainBottomTabList(userId: String, mainTabStr: String){
        var curUserInfo = getAppCurUserInfo(userId)
        if(curUserInfo == null){
            curUserInfo = AppUserInfo().apply {
                appUserId = userId
                appMainTabList = mainTabStr
            }
        }else{
            curUserInfo.appMainTabList = mainTabStr
        }
        insert(curUserInfo)
    }

    @WorkerThread
    private suspend fun getAppCurUserInfo(userId: String): AppUserInfo? {
        return appUserDao.getAppUserInfo(userId)
    }

    @WorkerThread
    private suspend fun insert(appUserInfo: AppUserInfo) {
        appUserDao.insert(appUserInfo)
    }

}